#!/usr/bin/python
import random
import cgi, cgitb
import MySQLdb
import os
from config import *
import sha
import smtplib
form = cgi.FieldStorage()
configure = config()
def headerPrint():
    print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Original ~ Shorten those long urls</title><link rel="stylesheet" href="styles.css" type="text/css" /></head><body><div id="wrap">	<div class="header">		<div class="title">			<h1><a href="http://origin.al.eu.org">Original</a></h1>			<h2>Python URL Shortening Service</h2>		</div>		<div class="nav">			<ul>				<li><a href="index.html">Home</a></li>			</ul>		</div>		<div class="clear"></div>	</div>	<div class="pagewrapper">		<div class="innerpagewrapper">			<div class="page">				<div class="content">					<p>'
def footerPrint():
    print '</p>				</div>				<div class="footer">					<p>&copy;&nbsp;2010&nbsp;<a href="http://origin.al.eu.org">Origin.al.eu.org</a>|Design: <a href="http://www.spyka.net">spyka webmaster</a></p> 				</div>			</div>		</div>	</div></div></body></html>'
print 'Content-type: text/html\n\n'
email = form.getvalue('email')
passwd = str(random.randint(10,99))
passwd = passwd+str(random.randint(10,99))
apikey = str(sha.new(email).hexdigest())
fromaddr = configure.fromAddress
toaddrs  = [email]
SUBJECT = "APIkey"
TEXT = "Dear User, \n    Your apikey has been created, username :"+email+" \npassword : "+passwd+"\napikey : "+apikey+"\nCheers,\nOriginal Team"
msg = """\
From: %s
To: %s
Subject: %s

%s
""" % (fromaddr, ", ".join(toaddrs), SUBJECT, TEXT)

headerPrint()
ip = cgi.escape(os.environ["REMOTE_ADDR"])
flag=0
try:
    db = MySQLdb.connect(host=configure.dbHostname,user=configure.dbUsername,passwd=configure.dbPassword,db=configure.dbName)
    sql = """insert into link_database_register(email,passwd,apikey,ipaddress) values('%s','%s','%s','%s')""" %(email,passwd,apikey,ip)
    db.query(sql)
    result = db.store_result()
except MySQLdb.Error, e:
    if(e.args[0]==1062):
        print "Email already registered... <a href='./register.html'>go back</a>"
        flag=1
    else:
        print "Error %d: %s" % (e.args[0], e.args[1])
#print result
if(flag!=1):
    print "<h2><font color='black'> API Key has been generated: "+apikey+"</font></h2>"
    print "Your ip has been recorded: "+ip
    try:
        server = smtplib.SMTP(configure.smtpHost,configure.smtpPort)
        server.set_debuglevel(2)
        server.login(configure.userName,configure.password)
        server.sendmail(fromaddr, toaddrs, msg)
        server.quit()
    except SMTPException, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
footerPrint()